package zk;


import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class zkdemo1 {

    public static void main(String[] args) {


        try {
            String hostport = "s60:2181";
            ZooKeeper zooKeeper = new ZooKeeper(hostport,
                    300000,  //sessionTimeout
                    null);     //创建一个ZooKeeper实例,不设置默认watcher  Watcher
            String path = "/consumers/12345/gizwits_raw/partition_0";
            // CreateMode.EPHEMERAL// 节点类型，有三种：PERSISTENT、EPHEMERAL、SEQUENTIAL。EPHEMERAL节点不允许有子节点
            /**
             *  zkp.create("/znodename", // 节点名称
             "znodedata".getBytes(), // 节点上的数据
             Ids.OPEN_ACL_UNSAFE,// ACL
             CreateMode.EPHEMERAL// 节点类型，有三种：PERSISTENT、EPHEMERAL、SEQUENTIAL。EPHEMERAL节点不允许有子节点
             );
             */

            Stat stat = new Stat();
            stat = zooKeeper.exists(path, false);    //查看path所代表的节点是否存在
            if(stat==null) {
                zooKeeper.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);    //创建一个节点
                System.out.println("创建节点..");
            }

            byte[] data = zooKeeper.getData(path,
                    false, // 是否设置监听器
                    stat);    //获取节点的信息及存储的数据
            System.out.println(stat);
            System.out.println(new String(data));

            //// 修改节点上存储的数据，需要提供version，version设为-1表示强制修改
            //{"consumer":{"id":"12345"},"offset":11354,"partition":0,"broker":{"host":"s5","port":9092},"topic":"gizwits_raw"}
    String dd="{\"consumer\":{\"id\":\"12345\"},\"offset\":10000,\"partition\":0,\"broker\":{\"host\":\"s5\",\"port\":9092},\"topic\":\"gizwits_raw\"}";
        //    zooKeeper.setData(path, "helloworld2".getBytes(), stat.getVersion());    //设置节点的数据
            zooKeeper.setData(path,dd.getBytes(), stat.getVersion());
            //  zooKeeper.delete(path, -1);    //删除节点
            zooKeeper.close();    //关闭实例
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
